package se.webbzon.boltzmann.imageset;

import java.awt.Image;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayDeque;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import se.webbzon.boltzmann.loader.Loader;
import se.webbzon.boltzmann.loader.LoaderException;
import se.webbzon.boltzmann.loader.LoaderUtilityPointer;
import se.webbzon.oschi01.filenameparser.FilenameParser;
import se.webbzon.oschi01.imageset.ImageSetLoader;
import se.webbzon.oschi01.resourceset.ResourceSet;
import se.webbzon.oschi01.resourceset.ResourceSetLoaderException;

public class ImageSetLoaderMap implements Loader {

	// A collection of resource names related to this loader
	private final static Collection<String> resourceNames = new ArrayDeque<String>();
		
	static {
		resourceNames.add("imageSet");
	}
	
	// A map containing all loaded image sets
	private final Map<String,ResourceSet<Image>> content;
	
	/*============================================================
	Constructors
	============================================================*/
	
	/** Creates a new image set loader which loads the image into a 
	 * local map. The map can be fetched by calling the method getMap().**/
	public ImageSetLoaderMap() {
		content = new HashMap<String,ResourceSet<Image>>();
	}
	
	/*============================================================
	Public Methods
	============================================================*/
	
	@Override public String getCategory() {
		return "imageSets";
	}

	@Override public Collection<String> getSupportedResources() {
		return resourceNames;
	}

	@Override public void load(LoaderUtilityPointer property, String resourceName,
			Map<String, String> resourceMap) throws LoaderException {
		final String name = resourceMap.get("name");
		final String expression = resourceMap.get("files");
		final ImageSetLoader loader = new ImageSetLoader();
		
		final Collection<String> filenames = FilenameParser.parse(expression);
		try {
			for (String filename : filenames)
				loader.addFromURL(new URL(property.getXMLURL(),filename));
		} catch (MalformedURLException | ResourceSetLoaderException e) {
			throw new LoaderException(e);
		}
		
		content.put(name, loader.getResourceSet());
	}
	
	/** Returns the image set map associated with this instance. **/
	public Map<String,ResourceSet<Image>> getMap() {
		return Collections.unmodifiableMap(content);
	}
	
}
